﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CRM.Extensions;
using CRM.Models;
using CRM.Models.SocialMarketing;
using Microsoft.EntityFrameworkCore;
using VK.Client;

namespace CRM.Services.SocialMarketing
{
    public class SocialMarketingTasksServer : BaseService
    {
        public Task<DbSetExtension.PaginateStruct<SocialMarketingTask>> Index()
        {
            return DbContext.SocialMarketingTasks
                .Where(m => m.OemId == CurrentUser.OemId)
                .OrderByDescending(m => m.Id)
                .ToPaginateAsync(Request);
        }

        public Task<SocialMarketingTask> Info(int id)
        {
            return DbContext.SocialMarketingTasks
                .Where(m => m.Id == id)
                .Where(m => m.OemId == CurrentUser.OemId)
                .FirstOrDefaultAsync();
        }

        public async Task Add(SocialMarketingTask model)
        {
            model.UserId = CurrentUser.Id;
            model.GroupId = CurrentUser.GroupId;
            model.CompanyId = CurrentUser.CompanyId;
            model.OemId = CurrentUser.OemId;
            
            await DbContext.SocialMarketingTasks.AddAsync(model);
            AddOperationLog(model, CurrentUser, "添加任务", SocialMarketingTaskOperationLog.OperationTypes.AddTasks);
            await DbContext.SaveChangesAsync();
        }

        public async Task SoftRemove(SocialMarketingTask model)
        {
            DbContext.SocialMarketingTasks.SoftRemove(model);
            AddOperationLog(model, CurrentUser, "移入回收站", SocialMarketingTaskOperationLog.OperationTypes.SoftDeleteTasks);
            await DbContext.SaveChangesAsync();
        }

        public async Task<bool> Publish(SocialMarketingTask row)
        {
            if (CurrentUser.HasOauthVk)
            {
                var client = new VkApiClient();
                // TODO: 社交发送图片
                var res = await client.Wall.Post(CurrentUser.SocialAccount.VkToken, new Dictionary<string, object>()
                {
                    {"message", row.Content}
                });

                if (res.State)
                {
                    row.VkPost = new VkPost() {Id = res.Content.Id};
                    row.State = SocialMarketingTask.PublishState.Published;
                    row.PublishedAt = DateTime.Now;
                    
                    AddOperationLog(row, CurrentUser, "发布任务成功", SocialMarketingTaskOperationLog.OperationTypes.PublishTasks);
                    await DbContext.SaveChangesAsync();
                    return true;
                }
                else
                {
                    row.State = SocialMarketingTask.PublishState.Error;
                    row.PublishedAt = DateTime.Now;
                    
                    AddOperationLog(row, CurrentUser, $"发布任务失败[{res.Error}]", SocialMarketingTaskOperationLog.OperationTypes.PublishTasks);
                    await DbContext.SaveChangesAsync();
                    Error = res.Error;
                    return false;
                }
                
            }
            else
            {
                Error = "未绑定社交帐号";
                return false;
            }
        }

        private void AddOperationLog(SocialMarketingTask row, User user, string name, SocialMarketingTaskOperationLog.OperationTypes type, string remark = "")
        {
            var operationLog = new SocialMarketingTaskOperationLog()
            {
                Name = name,
                OperationType = type,
                Remark = remark,
                SocialMarketingTaskId = row.Id,
                UserId = user.Id,
                GroupId = user.GroupId,
                CompanyId = user.CompanyId,
                OemId = user.OemId,
            };
            DbContext.Add(operationLog);
        }

        public async Task Edit(SocialMarketingTask row)
        {
            AddOperationLog(row, CurrentUser, "修改任务", SocialMarketingTaskOperationLog.OperationTypes.EditTasks);
            await DbContext.SaveChangesAsync();
        }

        public async Task Restore(SocialMarketingTask row)
        {
            DbContext.SocialMarketingTasks.Restore(row);
            AddOperationLog(row, CurrentUser, "恢复任务", SocialMarketingTaskOperationLog.OperationTypes.RestoreTasks);
            await DbContext.SaveChangesAsync();
        }

        public async Task ForceRemove(SocialMarketingTask row)
        {
            DbContext.SocialMarketingTasks.ForceRemove(row);
            AddOperationLog(row, CurrentUser, "删除任务", SocialMarketingTaskOperationLog.OperationTypes.DeleteTasks);
            await DbContext.SaveChangesAsync();
        }
    }
}